import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Admin
 * Date: 2022-05-18
 * Time: 20:59
 */
public class Main {

    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        boolean fly = false;
        Queue<TreeNode> que1 = new LinkedList<>();
        que1.offer(root);

        while(!que1.isEmpty()) {
            TreeNode cur1 = que1.peek();
            if( cur1.val == subRoot.val) {
                fly = isSameTree(cur1,subRoot);
            }

            cur1 = que1.poll();
            if(cur1.left != null) {
                que1.offer(cur1.left);
            }

            if(cur1.right != null) {
                que1.offer(cur1.right);
            }

            if(fly) {
                return fly;
            }
        }
        return false;
    }
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q != null) return false;
        if(p != null && q == null) return false;
        if(p == null && q == null) return true;

        if(p.val != q.val) {
            return false;
        }

        return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);

    }
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null) return false;

        if(isSameTree(root,subRoot))  return true;

        if(isSubtree(root.left,subRoot)) return true;

        if(isSubtree(root.right,subRoot)) return true;

        return false;
    }
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;

        int num = maxDepth(root.left);
        int sum = maxDepth(root.right);

        if(num >= 0 && sum >= 0 && Math.abs(num-sum) <=1) {
            return Math.max(num,sum)+1;
        }else {
            return -1;
        }
    }
    public boolean isBalanced(TreeNode root) {

        return maxDepth(root) >= 0;
    }
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        Queue<TreeNode> que = new LinkedList<>();
        if(root == null) return ret;

        que.offer(root);
        while(!que.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int size = que.size();

            while(size > 0) {
                TreeNode cur = que.poll();
                list.add(cur.val);
                size--;

                if(cur.left != null) {
                    que.offer(cur.left);
                }

                if(cur.right != null) {
                    que.offer(cur.right);
                }
            }
            ret.add(list);
        }
        return ret;
    }
}
